import Cookies from 'js-cookie'

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xDC00 && code <= 0xDFFF) i--
  }
  return s
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

import Layout from '@/layout'
import Layout2 from '@/layout/index2'
import Qibao from '@/admin'

export const loadView = (view) => { // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve)
}

export const loadAdminView = (view) => { // 路由懒加载
  return (resolve) => require([`@admin/views/${view}`], resolve)
}

/**
 * 将指定组件设置自定义名称
 *
 * @param {String} name 组件自定义名称
 * @param {Component | Promise<Component>} component
 * @return {Component}
 */
export function createCustomComponent(name, component) {
  return {
    name,
    data() {
      return {
        component: null
      }
    },
    async created() {
      if (component instanceof Promise) {
        try {
          const module = await component
          this.component = module?.default
        } catch (error) {
          console.error(`can not resolve component ${name}, error:`, error)
        }

        return
      }
      this.component = component
    },
    render(h) {
      return this.component ? h(this.component) : null
    }
  }
}

export function getFormatRoutes(menus, parentId = '0') {
  const routes = menus.filter(menu => {
    return menu.parentId === parentId
  }).sort((pre, next) => pre.orderId >= next.orderId ? 1 : -1).map((m) => {
    const children = getFormatRoutes(menus, m.id)
    const path = m.vueRouter ? m.vueRouter : ('/compage/' + m.id)
    const route = {
      path: path,
      component: m.parentId != '0'  ? Layout2 : Layout,
      name: 'compage' + m.id,
      hidden: !(m.type == 1 || (m.type == 4 && children.filter(i => !i.hidden).length)),
      meta: {
        title: m.name,
        icon: m.iconCode || 'el-icon-menu',
        code: m.id
      }
    }
    // 支持一级菜单配置组件
    if (m.parentId == '0' && m.type == 1 && children.length == 0) {
      route['component'] = Layout
      let child = {
        path: path,
        name: 'compage' + m.id,
        hidden: !(m.type == 1 || (m.type == 4 && children.filter(i => !i.hidden).length)),
        meta: {
          title: m.name,
          icon: m.iconCode || 'el-icon-menu',
          code: m.id
        }
      }
      if (m.vueComponent) {
        child['component'] = loadView(m.vueComponent)
      } else {
        child['component'] = Qibao.AdminCommonPage
      }
      route['children'] = [child]
      return route
    }
    if (children && children.length) {
      route['children'] = children
    }
    if (children && children.filter(i => !i.hidden).length) {

    } else {
      if (m.vueComponent) {
        const reg = m.vueComponent.match(/^@admin\/views\/(.*)$/)
        // 以@admin开头的是管理端
        if (reg && reg.length > 1) {
          console.log(reg[1])
          route['component'] = loadAdminView(reg[1])
        } else {
          route['component'] = loadView(m.vueComponent)
        }
      } else if (m.id === '2022052921186145061') {
        // 表单设计
        route['component'] = Qibao.AdminTableForm
      } else {
        route['component'] = Qibao.AdminCommonPage
      }
    }
    return route
  })
  return routes
}

// 路由三级转二级
export function getCompressRoutes(menus, parentId = '0', level = 1, routeLoaded=()=>{}) {
  const routes = []
  menus.filter(menu => {
    return menu.parentId === parentId
  }).sort((pre, next) => pre.orderId >= next.orderId ? 1 : -1).forEach((m) => {
    const path = m.vueRouter ? m.vueRouter : ('/compage/' + m.id)
    const children = getCompressRoutes(menus, m.id, level + 1, routeLoaded)
    const route = {
      path: path,
      component: m.parentId != '0' ? Layout2 : Layout,
      name: 'compage' + m.id,
      hidden: !(m.type == 1 || (m.type == 4 && children.length)),
      meta: {
        title: m.name,
        icon: m.iconCode || 'el-icon-menu',
        code: m.id,
        level: level,
        routerName: m.vueRouter
      }
    }
    // 支持一级菜单配置组件
    if (m.parentId == '0' && m.type == 1 && children.length == 0) {
      route['component'] = Layout
      let child = {
        path: path,
        name: 'compage' + m.id,
        hidden: !(m.type == 1 || (m.type == 4 && children.filter(i => !i.hidden).length)),
        meta: {
          title: m.name,
          icon: m.iconCode || 'el-icon-menu',
          code: m.id
        }
      }
      if (m.vueComponent) {
        child['component'] = loadView(m.vueComponent)
      } else {
        child['component'] = Qibao.AdminCommonPage
      }
      route['children'] = [child]
      routeLoaded && routeLoaded(route)
      routes.push(route)
      return
    }
    if (children && children.filter(i => !i.hidden).length) {

    } else {
      console.log(m);
      if (m.vueComponent) {
        const reg = m.vueComponent.match(/^@admin\/views\/(.*)$/)
        // 以@admin开头的是管理端
        if (reg && reg.length > 1) {
          console.log(reg[1])
          route['component'] = createCustomComponent('compage' + m.id, loadAdminView(reg[1]))
        } else {
          route['component'] = createCustomComponent('compage' + m.id, loadView(m.vueComponent))
        }
      } else {
        route['component'] = createCustomComponent('compage' + m.id, Qibao.AdminCommonPage)
      }
    }
    if (children && children.length) {
      if (level <= 1) {
        route['children'] = children
      } else {
        routes.push(...children)
      }
    }
    routeLoaded && routeLoaded(route)
    routes.push(route)
  })
  return routes
}

// 由一个组件，向上找到最近的指定组件
export function findComponentUpward(context, componentName) {
  let parent = context.$parent
  let name = parent.$options.name

  while (parent && (!name || [componentName].indexOf(name) < 0)) {
    parent = parent.$parent
    if (parent) name = parent.$options.name
  }
  return parent
}

// 由一个组件，向下找到最近的指定组件
export function findComponentDownward(context, componentName) {
  const childrens = context.$children
  let children = null

  if (childrens.length) {
    for (const child of childrens) {
      const name = child.$options.name

      if (name === componentName) {
        children = child
        break
      } else {
        children = findComponentDownward(child, componentName)
        if (children) break
      }
    }
  }
  return children
}

// 向下找到所有指定组件
export function findComponentsDownward(context, componentName) {
  return context.$children.reduce((components, child) => {
    if (child.$options.name === componentName) components.push(child)
    const foundChilds = findComponentsDownward(child, componentName)
    return components.concat(foundChilds)
  }, [])
}

// 找到指定组件的兄弟组件
export function findBrothersComponents(context, componentName, exceptMe = true) {
  const res = context.$parent.$children.filter(item => {
    return item.$options.name === componentName
  })
  const index = res.findIndex(item => item._uid === context._uid)
  if (exceptMe) res.splice(index, 1)
  return res
}

export function listToTree(list, typeid = 'TYPEID', id = 'ID', pid = null) {
  console.log(typeid, id)
  const isValidate = Array.isArray(list) && list.every(function (item) {
    return Object.hasOwnProperty.call(item, typeid) && Object.hasOwnProperty.call(item, id)
  })
  if (!isValidate) {
    // console.error(`缺少key:${typeid},${id}`)
    return list
  }
  const treeNodes = list.filter((item) => {
    if (Array.isArray(pid)) {
      return pid.includes((item[typeid] + '').trim())
    } else {
      return (item[typeid] + '').trim() == pid
    }
  }).sort((pre, next) => {
    return pre.order_id >= next.order_id ? 1 : -1
  }).map((item) => {
    const children = listToTree(list, typeid, id, item[id])
    if (children && children.length) {
      item['children'] = children
    }
    return item
  })
  return treeNodes
}

// 获取模板实例
export function getTemplateInstance(context) {
  return findComponentUpward(context, 'Tem1101') || findComponentUpward(context, 'Tem1102') || findComponentUpward(context, 'Tem1110') || findComponentUpward(context, 'Tem1111')
}

/**
 * Promise.all不进入catch
 * @param {p} items promise数组
 * @returns
 */
export function catchFun(items) {
  return items.map(item => item.catch((err) => Promise.resolve(err)))
}

/**
 * // 获取当前文件夹下所有文件
 * @param {*} dir 目录
 * @param {*} regExp 匹配文件正则
 * @param {*} useSub 表示是否检索子文件夹
 * @returns array
 */
export function getFiles(directory, regExp = /.vue$/, useSub = true) {
  const files = require.context(directory, useSub, regExp)
  const modules = []
  files.keys().forEach(item => {
    modules.push(files(item))
  })
  return modules
}

export function getType(arg) {
  return Object.prototype.toString.call(arg)
}

export function isObject(arg) {
  return getType(arg) === '[object Object]'
}

export function isBoolean(arg) {
  return getType(arg) === '[object Boolean]'
}

export function isNull(arg) {
  return getType(arg) === '[object Null]'
}

export function isArray(arg) {
  return Array.isArray(arg)
}

export function isString(arg) {
  return getType(arg) === '[object String]'
}

export function flatObject(data) {
  const uid = `uid_${Date.now()}`
  const process = (input, prefix = '', json = {}) => {
    Object.keys(input).forEach(key => {
      const val = input[key]
      const newKey = key

      if (!json.hasOwnProperty(`${prefix}${newKey}.`)) {
        json[`${prefix}${newKey}.`] = uid
      }

      if (typeof val === 'object' && !Array.isArray(val) && !!val) {
        json[`${prefix}${newKey}.`] = val
        process(val, `${prefix}${newKey}.`, json)
      } else {
        json[`${prefix}${newKey}.`] = val
      }
    })

    return json
  }

  const json = process(data)
  const result = {}
  Object.keys(json).forEach(key => {
    if (json[key] !== uid) {
      result[key.slice(0, -1)] = json[key]
    }
  })
  return result
}

/**
 * 展开多维为一维
 * USERID: {
   code: '',
   name: ''
 } => USERID.code: '', USERID.name: ''
 */
export function flatTableData(tableData) {
  return tableData.map(item => {
    return flatObject(item)
  })
}

export function getDic(typeid) {
  return window.$CodeSource[typeid]
}

// 有父子关系的数组，转为树形结构
export function arrayToTree(arr, pid = '0', primaryKey = 'code', parentKey = 'pcode') {
  const result = []
  const treeArr = arr
  treeArr.forEach((item, i) => {
    if (item[parentKey] == pid) {
      const a = arrayToTree(treeArr, item[primaryKey])
      if (a.length > 0) {
        // 递归调用此函数
        treeArr[i].children = a
      }
      result.push(treeArr[i])
    }
  })
  return result
}

/**
 * 判断是否显示refdata
 * 只有6、7类型才会显示
 */
export function tableShowRefdata(eleType) {
  return ['6', '7'].includes(eleType)
}

export function randomString(length) {
  var str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  var result = ''
  for (var i = length; i > 0; --i) {
    result += str[Math.floor(Math.random() * str.length)]
  }
  return result
}

export function collectPluck(oriObj, key) {
  const tmp = []
  oriObj.forEach((value) => {
    tmp.push(value[key])
  })
  return tmp
}

// 验证是否为blob格式
export async function blobValidate(data) {
  try {
    const text = await data.text()
    JSON.parse(text)
    return false
  } catch (error) {
    return true
  }
}

export function getUrlParam(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)') // 构造一个含有目标参数的正则表达式对象
  var r = window.location.search.substr(1).match(reg) // 匹配目标参数
  if (r != null) return unescape(r[2])
  return null // 返回参数值
}

export function getAppId() {
  // getUrlParam为了兼容应用预览
  return getUrlParam('appId') || sessionStorage.getItem('appId') || window?.g.appId || ''
}

export function getBaseApi() {
  return process.env.VUE_APP_BASE_API
}

// 生成验证码
export function createCode(canvasId, code) {
  const fontSizeMin = 35 // 最小字体
  const fontSizeMax = 55 // 最大字体
  const contentWidth = 220 // 画布宽度
  const contentHeight = 50 // 画布高度
  // 获取挂载到的DOM的id
  const canvas = document.getElementById(canvasId)
  canvas.width = contentWidth // 设置画布宽高
  canvas.height = contentHeight
  // 创建画布
  const cv = canvas.getContext('2d')
  cv.textBaseline = 'bottom'
  // 绘制背景
  cv.fillStyle = randomColor(200, 220)
  cv.fillRect(0, 0, contentWidth, contentHeight)
  // 8cv.font = 'italic 700 50px/100px 宋体'
  for (let i = 0; i < code.length; i++) {
    drawText(cv, code[i], i)
  }
  drawLine(cv)
  drawDot(cv)

  // 生成一个随机数
  function randomNum(min, max) {
    return Math.floor(Math.random() * (max - min) + min)
  }
  // 生成一个随机的颜色
  function randomColor(min, max) {
    const r = randomNum(min, max)
    const g = randomNum(min, max)
    const b = randomNum(min, max)
    return 'rgb(' + r + ',' + g + ',' + b + ')'
  }

  function drawText(cv, txt, i) {
    cv.fillStyle = randomColor(50, 160) // 随机生成字体颜色
    cv.font = randomNum(fontSizeMin, fontSizeMax) + 'px SimHei' // 随机生成字体大小
    const x = (i + 1) * (contentWidth / (code.length + 1))
    const y = randomNum(fontSizeMax, contentHeight - 5)
    var deg = randomNum(-30, 30)
    // 修改坐标原点和旋转角度
    cv.translate(x, y)
    cv.rotate((deg * Math.PI) / 180)
    cv.fillText(txt, 0, 0)
    // 恢复坐标原点和旋转角度
    cv.rotate((-deg * Math.PI) / 180)
    cv.translate(-x, -y)
  }

  function drawLine(cv) {
    // 绘制干扰线
    for (let i = 0; i < 4; i++) {
      cv.strokeStyle = randomColor(100, 200)
      cv.beginPath()
      cv.moveTo(randomNum(0, contentWidth), randomNum(0, contentHeight))
      cv.lineTo(randomNum(0, contentWidth), randomNum(0, contentHeight))
      cv.stroke()
    }
  }

  function drawDot(cv) {
    // 绘制干扰点
    for (let i = 0; i < 30; i++) {
      cv.fillStyle = randomColor(0, 255)
      cv.beginPath()
      cv.arc(
        randomNum(0, contentWidth),
        randomNum(0, contentHeight),
        1,
        0,
        2 * Math.PI
      )
      cv.fill()
    }
  }
}

export function windowClose() {
  if (navigator.userAgent.indexOf('Firefox') != -1 || navigator.userAgent.indexOf('Chrome') != -1) {
    window.location.href = 'about:blank'
    window.close()
  } else {
    window.opener = null
    window.open('', '_self')
    window.close()
  }
}

/**
 * 获取url参数
 * @param {url参数} name
 * @returns
 */
export function getUrlParam2(name) {
  const url = window.location.href
  // 通过 ? 分割获取后面的参数字符串
  const urlStr = url.split('?')[1] || ''
  // 创建空对象存储参数
  const obj = {}
  // 再通过 & 将每一个参数单独分割出来
  const paramsArr = urlStr.split('&')
  for (let i = 0, len = paramsArr.length; i < len; i++) {
    // 再通过 = 将每一个参数分割为 key:value 的形式
    const arr = paramsArr[i].split('=')
    obj[arr[0]] = arr[1]
  }
  return obj[name] || null
}

export function showMenu(layout) {
  let layoutArr = []
  if (layout) {
    layoutArr = layout.split(',')
  }
  if (layoutArr && layoutArr.length && layoutArr[0] === '0') {
    return false
  }
  return true
}
export function showNav(layout) {
  let layoutArr = []
  if (layout) {
    layoutArr = layout.split(',')
  }
  if (layoutArr && layoutArr.length && layoutArr[1] === '0') {
    return false
  }
  return true
}

const LAYOUT_KEY = '_layout'
// 设置布局
export function setLayout(layout) {
  sessionStorage.setItem(LAYOUT_KEY, layout)
}
export function getLayout() {
  return sessionStorage.getItem(LAYOUT_KEY) || ''
}

// 翻译
var language = localStorage.getItem('language') || 'zh-CN'
import qiBao_en from '@/assets/languages/en'
import qiBao_zhcn from '@/assets/languages/zh-CN'
var frameLocale = language === 'en-US' ? qiBao_en : qiBao_zhcn
export function $tra(attr, defaultValue) {
  let value = defaultValue
  try {
    const matchValue = attr.split('.').reduce((frameLocale, key) => frameLocale[key], frameLocale)
    value = typeof matchValue !== 'undefined' ? matchValue : value
  } catch (e) {}
  return value
}